<template>
  <div class="teacher-container">
    <div class="common-layout">
      <el-container class="layout-container">
        <!-- Sidebar Navigation -->
<!--        <el-aside class="sidebar">-->
<!--          <div class="sidebar-content">-->
<!--            <h5 class="sidebar-title">Teacher Space</h5>-->
<!--            <el-menu-->
<!--                default-active="1"-->
<!--                class="el-menu-vertical-demo"-->
<!--                background-color="#f8fafc"-->
<!--                active-text-color="#4f46e5"-->
<!--            >-->
<!--              <el-menu-item index="1" class="menu-item">-->
<!--                <el-icon><setting /></el-icon>-->
<!--                <span>My Courses</span>-->
<!--              </el-menu-item>-->
<!--            </el-menu>-->
<!--          </div>-->
<!--        </el-aside>-->

        <el-aside class="sidebar">
          <div class="sidebar-content">
          <h5 class="sidebar-title">
            <div style="margin-left:20px;display:flex;align-items: center;float:left;vertical-align: middle;height:100%">
              <a :href="'/#/lession?courseid='+courseid+'&name='+name"><el-icon><Back /></el-icon></a>&nbsp;
            </div>&nbsp;
            {{name}}

          </h5>
<!--          <el-row class="tac">-->
<!--            <el-col :span="24">-->

<!--              <h3 class="mb-2">-->


<!--              </h3>-->
              <el-menu
                  default-active="1"
                  class="el-menu-vertical-demo"
                  background-color="#f8fafc"
                  active-text-color="#4f46e5"
              >

                <el-menu-item index="1" class="menu-item">
                  <a :href="'/#/classroom?courseid='+courseid+'&lessionid='+lessionid+'&name='+name"><el-icon><Document /></el-icon>
                    <span>Material</span></a>
                </el-menu-item>
                <el-menu-item index="2" class="menu-item">
                  <a :href="'/#/classroomaudio?courseid='+courseid+'&lessionid='+lessionid+'&name='+name"><el-icon><VideoPlay /></el-icon>
                    <span>Recoding</span></a>
                </el-menu-item>
                <el-menu-item index="3" class="menu-item">
                  <a :href="'/#/classroomscript?courseid='+courseid+'&lessionid='+lessionid+'&name='+name"><el-icon><Service /></el-icon>
                    <span>transcript</span></a>
                </el-menu-item>
              </el-menu>
<!--            </el-col>-->
<!--          </el-row>-->
          </div>

        </el-aside>

        <!-- Main Content -->
        <el-main class="main-content">
          <el-row>
            <div class="page-header">
<!--            <el-col :span="24" class="topdiv">-->
              <el-button :icon="Upload" type="primary" @click="showdialog()" v-if="lessionfiledata.isMyCourse">upload</el-button>
<!--            </el-col>-->
            </div>
            <el-col :span="24">

<!--              <div class="content-panel"  v-for="item in lessionfiledata.list">-->
<!--                <div class="content">-->
<!--                  {{item.name}}&nbsp;&nbsp;{{item.filename}}&nbsp;&nbsp;{{item.filesize}}-->
<!--                </div>-->
<!--                <div class="button">-->
<!--                  <el-button type="success" :icon="Download" circle @click="doDownload(item.filepath,item.filename)"></el-button>-->
<!--                  <el-button type="primary" :icon="Edit" circle @click="doEdit(item)" v-if="lessionfiledata.isMyCourse"/>-->
<!--                  <el-button type="danger" :icon="Delete" circle @click="doDelete(item.id)" v-if="lessionfiledata.isMyCourse"/>-->
<!--                </div>-->
<!--              </div>-->
<!--            -->

              <div class="course-list">
                <div
                    class="course-card"
                    v-for="item in lessionfiledata.list"
                    :key="item.id"
                >
                  <div class="course-info">
                    <h3 class="course-name">{{item.filename}}&nbsp;&nbsp;{{item.filesize}}</h3>
                    <!--                <span class="course-year" v-if="item.marjor">-->
                    <!--                  {{ getYearLabel(item.marjor) }}-->
                    <!--                </span>-->
                  </div>
                  <div class="course-actions">
                    <el-tooltip content="View Lessons" placement="top">
                      <el-button
                          type="success"
                          :icon="Download"
                          circle
                          @click="doDownload(item.filepath,item.filename)"
                          class="action-btn"
                      />
                    </el-tooltip>
                    <el-tooltip content="Edit Course" placement="top" v-if="lessionfiledata.isMyCourse">
                      <el-button
                          type="primary"
                          :icon="Edit"
                          circle
                          @click="doEdit(item)"
                          class="action-btn"
                      />
                    </el-tooltip>
                    <el-tooltip content="Delete Course" placement="top" v-if="lessionfiledata.isMyCourse">
                      <el-button
                          type="danger"
                          :icon="Delete"
                          circle
                          @click="doDelete(item.id)"
                          class="action-btn"
                      />
                    </el-tooltip>
                  </div>
                </div>
              </div>


            </el-col>
          </el-row>

        </el-main>
      </el-container>
    </div>


    <el-dialog v-model="dialogFormVisible.visible" title="save&edit" width="500">
      <el-form>
        <el-form-item label="name" :label-width="formLabelWidth">
          <el-input v-model="onelessionfile.id" type="hidden"/>
          <el-input v-model="onelessionfile.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="filepath" :label-width="formLabelWidth">
          <el-upload
              ref="upload"
              class="upload-demo"
              action=""
              :limit="1"
              :on-exceed="handleExceed"
              :on-change="handleChange"
              :auto-upload="false"
          >
            <template #trigger>
              <el-button type="primary">select file</el-button>
            </template>
            <!-- <template #tip>
              <div class="el-upload__tip text-red">
                limit 1 file, new file will cover the old file
              </div>
            </template> -->
          </el-upload>
          &nbsp;
          <label>{{onelessionfile.filename}}</label>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible.visible = false">Cancel</el-button>
          <el-button type="primary" @click="doSubmit()">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">

//import TopHeader from '../../components/TopHeader.vue' // 引用Header组件
//import TopBottom from '../../components/TopBottom.vue' // 引用Header组件

import {
  Upload,
  Download,
  Delete,
  Edit,
  Message,
  Search,
  Star,
} from '@element-plus/icons-vue'
import { reactive,ref,onMounted} from 'vue'
import { useRoute,useRouter } from 'vue-router'
import { genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { uploadImage,download,isMyCourse } from '../../api/course.ts'
import { getMyLessionFileList,deleteLessionFile,saveLessionFile } from '../../api/lessionfile.ts'

const route = useRoute()
const currentRoute = useRouter()
const courseid = route.query.courseid
const lessionid = route.query.lessionid
const name = route.query.name
const upload = ref<UploadInstance>()
const dialogFormVisible = reactive({
  visible:false
})
const formLabelWidth = '140px'

//单门onelessionfile，增加和编辑使用
const onelessionfile = reactive({
  id:null,
  name:'',
  filename:'',
  filesize:'',
  filepath:'',
  courseid:courseid,
  lessionid:lessionid
})
//lessionfile列表
const lessionfiledata = reactive({
  list:[],
  isMyCourse:false
})

onMounted(() => {
  loaddata();
})

function loaddata()
{
  getMyLessionFileList({"lessionid":lessionid}).then((res) => {
    if (res.code == 200)
    {
      lessionfiledata.list = res.data;
    }
  })
  isMyCourse({"courseid":courseid}).then((res) => {
    if (res.code == 200)
    {
      lessionfiledata.isMyCourse = res.data;
    }
  })
}
function showdialog()
{
  dialogFormVisible.visible = true
  onelessionfile.id=null
  onelessionfile.name=''
  onelessionfile.filename=''
  onelessionfile.filesize=''
  onelessionfile.filepath=''
}
function doEdit(item)
{
  dialogFormVisible.visible = true
  onelessionfile.id=item.id
  onelessionfile.name=item.name
  onelessionfile.filename=item.filename
  onelessionfile.filesize=item.filesize
  onelessionfile.filepath=item.filepath
}
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}
function formatBytes(bytes, decimals = 2) {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
function handleChange(file, fileList){
  //upload.value!.clearFiles()
  const file2 = file.raw as UploadRawFile
  //file2.uid = genFileId()
  //upload.value!.handleStart(file2)
  onelessionfile.filename = file2.name
  onelessionfile.filesize = formatBytes(file2.size,2)

  const param = new FormData();
  let fileType = file2.type
  fileType = fileType.substr(fileType.lastIndexOf('/') + 1)
  const imgName = new Date().getTime();
  param.append("file", file2, imgName + "." + fileType)
  param.append("targetpath", '/lessionfile')

  uploadImage(param).then((res) => {
    if (res.code == 200)
    {
      onelessionfile.filepath = res.data.filepath
    }
  })
  upload.value!.clearFiles()
}
function doDelete(id)
{
  deleteLessionFile({"id":id}).then((res) => {
    if (res.code == 200)
    {
      //更新下视图数据
      loaddata();
    }
  })
}
function doDownload(filepath,filename)
{
  download({"filepath":filepath}).then((res) => {
    downloadLink(res,filename);
  })

}

function downloadLink(data, title) {
  var elink = document.createElement("a");
  elink.download = title;
  elink.style.display = "none";
  var blob = new Blob([data]);
  elink.href = window.URL.createObjectURL(blob);
  document.body.appendChild(elink);
  elink.click();
  document.body.removeChild(elink);
}

function doSubmit()
{
  dialogFormVisible.visible = false
  saveLessionFile(onelessionfile).then((res) => {
    if (res.code == 200)
    {
      //更新下视图数据
      loaddata();
    }
  })
}
</script>

<style lang="less" scoped>
.teacher-container {
  height: 100vh;
  background-color: #f8fafc;
}

.layout-container {
  height: 100%;
}

.sidebar {
  width: 220px !important;
  background-color: #f8fafc;
  border-right: 1px solid #e2e8f0;

  .sidebar-content {
    padding: 20px 0;

    .sidebar-title {
      color: #64748b;
      font-size: 16px;
      font-weight: 600;
      padding: 0 20px 15px;
      margin: 0;
      border-bottom: 1px solid #e2e8f0;
    }
  }

  .menu-item {
    margin: 5px 10px;
    border-radius: 6px;
    transition: all 0.3s ease;

    &:hover {
      background-color: #eef2ff !important;
      color: #4f46e5 !important;
    }

    &.is-active {
      background-color: #eef2ff !important;
      color: #4f46e5 !important;
      font-weight: 500;
    }
  }
}

.main-content {
  padding: 30px !important;
  background-color: white;
  border-radius: 12px 0 0 0;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.05);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;

  .page-title {
    color: #1e293b;
    font-size: 24px;
    margin: 0;
  }

  .add-course-btn {
    background-color: #4f46e5;
    border: none;
    padding: 10px 20px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(79, 70, 229, 0.2);
    transition: all 0.3s ease;

    &:hover {
      background-color: #4338ca;
      transform: translateY(-2px);
    }

    .el-icon {
      margin-right: 8px;
    }
  }
}

.course-list {
  display: grid;
  grid-template-columns: 1fr;
  gap: 15px;
}

.course-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  border: 1px solid #f1f5f9;

  &:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    border-color: #e0e7ff;
  }

  .course-info {
    .course-name {
      font-size: 16px;
      font-weight: 600;
      color: #1e293b;
      margin: 0 0 5px 0;
    }

    .course-year {
      font-size: 13px;
      color: #64748b;
      background-color: #f1f5f9;
      padding: 3px 8px;
      border-radius: 4px;
    }
  }

  .course-actions {
    display: flex;
    gap: 10px;

    .action-btn {
      transition: all 0.2s ease;

      &:hover {
        transform: scale(1.1);
      }
    }
  }
}

.course-dialog {
  :deep(.el-dialog) {
    border-radius: 12px;
    overflow: hidden;
  }

  :deep(.el-dialog__header) {
    border-bottom: 1px solid #f1f5f9;
    padding: 20px;
    margin-right: 0;

    .el-dialog__title {
      font-weight: 600;
      color: #1e293b;
    }
  }

  :deep(.el-dialog__body) {
    padding: 20px;
  }

  //.dialog-input,
  .dialog-select {
    width: 100%;

    :deep(.el-input__inner) {
      border-radius: 8px;
      border: 1px solid #e2e8f0;
      height: 40px;

      &:focus {
        border-color: #4f46e5;
        box-shadow: 0 0 0 1px rgba(79, 70, 229, 0.2);
      }
    }
  }

  .status-radio {
    :deep(.el-radio__inner) {
      border-color: #cbd5e1;
    }

    :deep(.el-radio__input.is-checked .el-radio__inner) {
      background-color: #4f46e5;
      border-color: #4f46e5;
    }

    :deep(.el-radio__label) {
      color: #475569;
    }
  }

  .upload-btn {
    background-color: #f1f5f9;
    border: none;
    color: #4f46e5;
    border-radius: 8px;

    &:hover {
      background-color: #e0e7ff;
    }

    .el-icon {
      margin-right: 8px;
    }
  }

  .image-preview {
    margin-top: 15px;

    img {
      width: 100px;
      height: 100px;
      object-fit: cover;
      border-radius: 8px;
      border: 1px solid #e2e8f0;
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;

    .cancel-btn {
      border-radius: 8px;
      border: 1px solid #e2e8f0;

      &:hover {
        color: #4f46e5;
        border-color: #c7d2fe;
      }
    }

    .confirm-btn {
      background-color: #4f46e5;
      border: none;
      border-radius: 8px;

      &:hover {
        background-color: #4338ca;
      }
    }
  }
}

@media (max-width: 768px) {
  .sidebar {
    width: 100% !important;
    height: auto !important;
    border-right: none;
    border-bottom: 1px solid #e2e8f0;
  }

  .main-content {
    padding: 20px !important;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .course-card {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;

    .course-actions {
      width: 100%;
      justify-content: flex-end;
    }
  }

  .course-dialog {
    width: 90% !important;
  }
}
</style>
